//
//  DBManageController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2015/1/2.
//  Copyright (c) 2015年 Tank. All rights reserved.
//

#import "DBManageController.h"

@implementation DBManageController
@synthesize DB,vcardRequestArray,vcardResultArray;
+(DBManageController *)sharedInstance
{
    static DBManageController *_DBManageController;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _DBManageController = [[DBManageController alloc] init];
        _DBManageController.DB = [DBClass sharedInstance];
        
        
    });
    
    return _DBManageController;
}
//表格
-(NSEntityDescription *)getEntityEdscription:(NSString *)EntityEdscriptionName
{
    
    if (EntityEdscriptionName == nil) {
        return nil;
    }
    return [NSEntityDescription entityForName:EntityEdscriptionName inManagedObjectContext:[DB managedObjectContext]];
}
//篩選
-(NSPredicate *) predicate :(NSString *)predicateString
{
    if (predicateString == nil)
    {
        return nil;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
    
    return predicate;
}
//排列
- (NSSortDescriptor * )sortDescriptor:(NSString *)sortString ascending:(BOOL)ascending
{
 
    if (sortString == nil) {
        return nil;
    }
    NSSortDescriptor *sortDescriptor=[[NSSortDescriptor alloc]initWithKey:sortString ascending:ascending];//先做一個分類描述 描述內容的key 就是到時候陣列裡面的關鍵字 後面是升降
    return sortDescriptor;
}


-(NSArray *)coreDataSearchWithEntityName:(NSString *)entityName Predicate:(NSString *)predicateString sortDescriptor:(NSString *)sortString ascending:(BOOL)ascending
{
    if (entityName == nil) {
        return nil;
    }
    
    //取得表格
    NSEntityDescription *entity = [self getEntityEdscription:entityName];
    
    //取得斷言
    NSPredicate *predicate = [self predicate:predicateString];
    
    //取得排序
    NSSortDescriptor *sortDescriptor= [self sortDescriptor:sortString ascending:ascending];
    
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    [fetch setEntity:entity];
    [fetch setPredicate:predicate];
    [fetch setSortDescriptors:@[sortDescriptor]];
    
    NSArray *resultArray = [[DB managedObjectContext] executeFetchRequest:fetch error:nil];

    return resultArray;
    
}


//取得單一個朋友
-(FiendFriend *)getOneFriend:(NSString *)predicateString
{
    NSPredicate *predicate = [self predicate:predicateString];
    NSFetchRequest *request;
    if (request==nil) {
        request = [[NSFetchRequest alloc] init];
    }
    request.entity= [self getEntityEdscription:@"FriendRoster"];
    request.predicate = predicate;
    NSError *error;
    NSArray *results = [[DB managedObjectContext] executeFetchRequest:request
                                                                error:&error];
    if (results.count==1) {
        return [results firstObject];
    }else
    {
        return nil;
    }
}

//取得全部朋友
-(NSArray *)getRoster
{
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    
    NSEntityDescription *entity = [self getEntityEdscription:@"FriendRoster"];
    
    [fetch setEntity:entity];
    //朋友列表
    NSArray *array_myRoster =[DB.managedObjectContext executeFetchRequest:fetch error:nil];
    
    return array_myRoster;
}


//新增朋友
-(FriendRoster *)addFriendJid:(NSString *)jid
{
    
    //取得朋友 檢測有沒有
    FriendRoster *friendRoster = (FriendRoster *)[self getOneFriend:[NSString stringWithFormat:@"jid CONTAINS[cd] '%@'",jid]];
    
    if (friendRoster ==nil) {
        friendRoster = (FriendRoster*)[NSEntityDescription insertNewObjectForEntityForName:@"FriendRoster"
                                     
                                                                  inManagedObjectContext:[DB managedObjectContext]];
        // 從參數設定物件初始值
        friendRoster.jid = [self jidAdjustWithJID:jid];
        
        [self checkNewToy:friendRoster.jid];
        
        NSError* error = nil;
        if (![[DB  managedObjectContext] save:&error]) {
            NSLog(@"新增 遇到錯誤");
            return nil;
        }else
        {
            NSLog(@"新增 jid 成功");
            return friendRoster;
        }
    }else
    {
        return friendRoster;
    }
    
}



//新增多個朋友
-(void)setFriend:(NSArray *)friends
{
    if (vcardRequestArray == nil) {
        vcardRequestArray = [[NSMutableArray alloc]init];
    }

    NSArray *allRoster = [self getRoster];
    [vcardRequestArray addObjectsFromArray:friends];
    
    //要加入的朋友 列表
    [friends enumerateObjectsUsingBlock:^(NSString *jidFromXMPP, NSUInteger idx, BOOL *stopContrast) {
        
        //DB的列表
        [allRoster enumerateObjectsUsingBlock:^(FriendRoster *friendRoster, NSUInteger idx, BOOL *stop) {
            
            //如果一樣 表示已經加過好友 就移除 要加入的朋友
            if ([friendRoster.jid isEqualToString:jidFromXMPP]) {

                [vcardRequestArray removeObject:jidFromXMPP];

                *stop = YES;
            }
            
        }];
        
    }];
    
    
    for (NSString *jid in vcardRequestArray)
    {
        //上面一段已經過濾掉已新增的Jid
       FriendRoster *roster =  [self addFriendJid:jid];
        
        //發送vcard請求
        xclient_vcard_get((char *)[roster.jid UTF8String]);
    }
}

-(void)getVcardResult:(NSDictionary *)vcardInfo
{
    //=======資料的處理=======
    NSString *jid = [self jidAdjustWithJID:[vcardInfo objectForKey:@"vcard_get"]];
    NSString *nickName = [vcardInfo objectForKey:@"NICKNAME"];
    NSString *imagePath = [self adjustPathWithPath:[vcardInfo objectForKey:@"PHOTO_PATH"]];
    
    //=======資料的處理=======
    
    
    //=======資料的更新=======
    FriendRoster *friendRoster = (FriendRoster *)[self getOneFriend:[NSString stringWithFormat:@"jid CONTAINS[cd] '%@'",jid]];

    if (friendRoster) {
     
        friendRoster.jid_noDomain = [jid stringByReplacingOccurrencesOfString:@"@bbserver-virtualbox" withString:@""];
        
        friendRoster.nickName = nickName;
        
        friendRoster.imagePath = imagePath;
        
        friendRoster.type = [jid hasPrefix:@"toy"] ? [NSNumber numberWithInteger:0] : [NSNumber numberWithInteger:1];
        
        friendRoster.createdTime = [NSDate date];
        
        [DB saveContext];
    }
    //=======資料的更新=======
    
    
    
    //===========這一段是在處理新增jid 完畢後 要去更新使用者列表======
    [vcardRequestArray removeObject:jid];
    if (vcardRequestArray.count == 0) {
        vcardRequestArray = nil;
        //更新所有頁面的roster資訊
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RosterSync" object:nil];
    }
    //===========這一段是在處理新增jid 完畢後 要去更新使用者列表======

}

-(void)changePresenceOnAndOffWithPresence:(BOOL)presence whoseJid:(NSString *)Jid
{
    //取得 roster
    FriendRoster *roster = [self addFriendJid:Jid];
    
    if (roster) {
        
        //修改狀態
        roster.isOnline = [NSNumber numberWithBool:presence];
        
    }
    
    //發送vcard請求
    //xclient_vcard_get((char *)[roster.jid UTF8String]);
    
}







//==============房間===============
-(void)whoseRoom:(NSString *)jid completionBlock:(void(^)(Room *room))completion failureBlock:(void(^)(BOOL noRoom))failureBlock
{
    
    NSPredicate *predicate = [self predicate:[NSString stringWithFormat:@"whose CONTAINS[cd] '%@'",jid]];
    NSFetchRequest *request;
    if (request==nil) {
        request = [[NSFetchRequest alloc] init];
    }
    request.entity= [self getEntityEdscription:@"Room"];
    request.predicate = predicate;
    NSError *error;
    NSArray *results = [[DB managedObjectContext] executeFetchRequest:request
                                                                error:&error];
    if (results.count==1) {
        if (completion) {
            completion([results firstObject]);
        }
    }else
    {
        if (failureBlock) {
            failureBlock(NO);
        }
    }
    
}

//==========對外的窗口==========
-(void)checkNewToy:(NSString *)toyJID
{
    if (self.getNewToyDelegate && [self.getNewToyDelegate respondsToSelector:@selector(getNewToyResult:)]) {
        
        if ([toyJID hasPrefix:@"toy"])
        {
            [self.getNewToyDelegate getNewToyResult:toyJID];
        }
    }
}

//================method================
-(NSString *)jidAdjustWithJID:(NSString *)jid
{
    NSString *adjustJID = jid;
    
    //有存在 / 就把文字擷取到 /之前的
    if ([adjustJID rangeOfString:@"/"].location != NSNotFound)
        adjustJID = [adjustJID substringToIndex:[adjustJID rangeOfString:@"/"].location];
    
    
    if ([adjustJID rangeOfString:@"@bbserver-virtualbox"].location == NSNotFound)
        adjustJID = [adjustJID stringByAppendingString:@"@bbserver-virtualbox"];
    
    return adjustJID;
}

-(NSString *)adjustPathWithPath:(NSString *)path
{
    NSString *adjustPath = path;
    
    adjustPath = [adjustPath stringByReplacingOccurrencesOfString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] withString:@""];
    
    return adjustPath;
}
@end
